package com.vichat.common.context;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component("contextHolder")
public class ContextHolder implements ApplicationContextAware {
	/**
	 * 保存HttpServletResponse的线程局部变量.
	 */
	private static final ThreadLocal<HttpServletResponse> responseThreadLocal = new ThreadLocal<HttpServletResponse>();
	/**
	 * 保存HttpServletRequest的线程局部变量.
	 */
	private static final ThreadLocal<HttpServletRequest> requestThreadLocal = new ThreadLocal<HttpServletRequest>();

	private static ApplicationContext applicationContext;

	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	@SuppressWarnings("unchecked")
	public static <T> T getBean(String beanId) {
		return (T) applicationContext.getBean(beanId);
	}

	public void setApplicationContext(ApplicationContext context) {
		Assert.notNull(context, "ApplicationContext can not be null");
		applicationContext = context;
	}

 

	public static HttpServletRequest getRequest() {
		return requestThreadLocal.get();
	}

	public static HttpServletResponse getResponse() {
		return responseThreadLocal.get();
	}

	public static HttpSession getHttpSession() {
		return requestThreadLocal.get().getSession();
	}

	public static void setHttpRequestResponseHolder(HttpServletRequest request, HttpServletResponse response) {
		responseThreadLocal.set(response);
		requestThreadLocal.set(request);
	}

	public static void clean() {
		responseThreadLocal.remove();
		requestThreadLocal.remove();
	}
	

}
